package com.szbmyoubao.app.ui.scan

import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.provider.MediaStore
import android.text.TextUtils
import android.view.View
import android.widget.FrameLayout
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import com.ellecity06.common.utils.logD
import com.ellecity06.cwhiskymall.R
import com.ellecity06.cwhiskymall.databinding.ActivityScanBinding
import com.gyf.immersionbar.ktx.immersionBar
import com.huawei.hms.hmsscankit.OnLightVisibleCallBack
import com.huawei.hms.hmsscankit.OnResultCallback
import com.huawei.hms.hmsscankit.RemoteView
import com.huawei.hms.hmsscankit.ScanUtil
import com.huawei.hms.ml.scan.HmsScan
import com.huawei.hms.ml.scan.HmsScanAnalyzerOptions

/**
 * @author ellecity06
 * @time 2025/4/1 19:07
 * @des
 */
class ScanActivity : AppCompatActivity() {
    private lateinit var binding: ActivityScanBinding
    var mScreenWidth = 0
    var mScreenHeight = 0


    val img = intArrayOf(R.drawable.scankit_flashlight_on, R.drawable.scankit_flashlight_off)
    var remoteView: RemoteView? = null

    companion object {
        const val SCAN_RESULT = "scanResult"
        const val REQUEST_CODE_PHOTO = 0X1113
        const val SCAN_FRAME_SIZE = 240
    }

    private var onScanSuccess: ((String) -> Unit)? = ScanDelegate.instance.getScanResultDelegate()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityScanBinding.inflate(layoutInflater)
        setContentView(binding.root)
        immersionBar {
            transparentBar()
            statusBarDarkFont(true)
            navigationBarColor(com.ellecity06.common.R.color.white)
            navigationBarEnable(false)
            navigationBarWithKitkatEnable(false)
            titleBar(binding.toolBar)
        }
        onScanSuccess = ScanDelegate.instance.getScanResultDelegate()
        val dm = resources.displayMetrics
        val density = dm.density

        mScreenWidth = resources.displayMetrics.widthPixels
        mScreenHeight = resources.displayMetrics.heightPixels

        val scanFrameSize = (SCAN_FRAME_SIZE * density).toInt()
        val rect = Rect()
        rect.left = mScreenWidth / 2 - scanFrameSize / 2
        rect.right = mScreenWidth / 2 + scanFrameSize / 2
        rect.top = mScreenHeight / 2 - scanFrameSize / 2
        rect.bottom = mScreenHeight / 2 + scanFrameSize / 2
        remoteView = RemoteView.Builder().setContext(this).setBoundingBox(rect).setFormat(HmsScan.ALL_SCAN_TYPE).build()
        remoteView?.setOnLightVisibleCallback(OnLightVisibleCallBack { visible ->
            if (visible) {
                binding.flushBtn.visibility = View.VISIBLE
            }
        })
        binding.backImg.setOnClickListener { onBackPressed() }
        remoteView?.setOnResultCallback(OnResultCallback { result ->
            if (result != null && result.isNotEmpty() && result[0] != null && !TextUtils.isEmpty(result[0].getOriginalValue())) {
                result.forEach {
                    logD("扫码结果=${it.originalValue}")
                }
                val hmsScan = result[0]
                if (onScanSuccess != null) {
                    finish()
                    onScanSuccess?.invoke(hmsScan.getOriginalValue())
                    onScanSuccess = null
                } else {
                    val intent = Intent()
                    intent.putExtra(SCAN_RESULT, hmsScan.getOriginalValue())
                    setResult(RESULT_OK, intent)
                    finish()
                }

            }
        })
        remoteView?.onCreate(savedInstanceState)
        val params = FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)
        binding.rim.addView(remoteView, params)
        setBackOperation()
        setPictureScanOperation()
        setFlashOperation()
    }


    private fun setPictureScanOperation() {
        binding.imgBtn.setOnClickListener(View.OnClickListener {
            val pickIntent = Intent(
                Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            )
            pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
            this@ScanActivity.startActivityForResult(pickIntent, REQUEST_CODE_PHOTO)
        })
    }

    private fun setFlashOperation() {
        binding.flushBtn.setOnClickListener {
            if (remoteView?.lightStatus == true) {
                remoteView?.switchLight()
                binding.flushBtn.setImageResource(img[1])
            } else {
                remoteView?.switchLight()
                binding.flushBtn.setImageResource(img[0])
            }
        }
    }

    private fun setBackOperation() {
//        binding.flushBtn.setOnClickListener(View.OnClickListener { finish() })
    }

    override fun onStart() {
        super.onStart()
        remoteView?.onStart()
    }

    override fun onResume() {
        super.onResume()
        remoteView?.onResume()
    }

    override fun onPause() {
        super.onPause()
        remoteView?.onPause()
    }

    override fun onStop() {
        super.onStop()
        remoteView?.onStop()
    }

    override fun onDestroy() {
        super.onDestroy()
        remoteView?.onDestroy()
        onScanSuccess = null
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_PHOTO && data != null) {
            try {
                val bitmap = MediaStore.Images.Media.getBitmap(this.contentResolver, data.data)
                val hmsScans = ScanUtil.decodeWithBitmap(this@ScanActivity, bitmap, HmsScanAnalyzerOptions.Creator().setPhotoMode(true).create())
                if (hmsScans != null && hmsScans.size > 0 && hmsScans[0] != null && !TextUtils.isEmpty(hmsScans[0]!!.getOriginalValue())) {
                    if (onScanSuccess != null) {
                        finish()
                        onScanSuccess?.invoke(hmsScans[0].getOriginalValue())
                        onScanSuccess = null
                    }
                    val intent = Intent()
                    intent.putExtra(SCAN_RESULT, hmsScans[0])
                    setResult(RESULT_OK, intent)
                    finish()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

}